<template>
	<div class="add_activity">
		<head-back-title :title="title"></head-back-title>
		<el-card class="box-card">
			<div slot="header" class="clearfix title">活动信息</div>
			<el-row :gutter="20">
				<el-col :span="12">
					<div class="activity-info">
						<el-form ref="activeInfo" :model="activeInfo" :rules="activeRules" label-width="120px">
							<el-form-item label="活动类型:" prop="type">
								<el-radio-group v-model="activeInfo.type" >
									<el-radio :label="1">分销裂变</el-radio>
									<el-radio :label="2">拼团裂变</el-radio>
								</el-radio-group>
							</el-form-item>
							<el-form-item label="活动主图:" prop="image">
								<el-upload class="avatar-uploader" action="fakeaction" :show-file-list="false" :http-request=" function(res) { return upload(res, 0); } ">
									<img v-if="activeInfo.image" :src="activeInfo.image" class="avatar">
									<i v-else class="el-icon-plus avatar-uploader-icon"></i>
								</el-upload>
								<p style="color: #999;">建议尺寸750*750px(或正方形)</p>
							</el-form-item>
							<el-form-item label="活动轮播图:" prop="goods_simg">
								<div class="case-img-upload">
									<div class="case-img-upload-btns" v-if="goods_simg.length < 4 ">
										<el-upload :disabled="disabled" ref="upload" action="fakeaction" :show-file-list="false" :http-request="function (res) { return upload(res,3)}" multiple accept="image/*">
											<el-button :disabled="disabled" type="primary" size="small">上传图片</el-button>
										</el-upload>
										<div class="el-upload__tip">小于500KB,建议尺寸750*750px(或正方形)</div>
									</div>
									<div class="case-img-upload-imgs" v-if="goods_simg.length">
										<div v-for="(data,index) in goods_simg" :key="index" class="vice_big_box">
											<i class="el-icon-error" @click="delVice(index,1)"></i>
											<el-image :src="data" fit="contain"></el-image>
										</div>
									</div>
								</div>
							</el-form-item>
							<el-form-item label="活动标题:" prop="title">
								<el-input v-model="activeInfo.title" maxlength="40" show-word-limit></el-input>
							</el-form-item>
							<el-form-item label="活动副标题:" prop="subtitle">
								<el-input v-model="activeInfo.subtitle" maxlength="100" show-word-limit></el-input>
							</el-form-item>
							<el-form-item label="购票名称:" prop="name">
								<el-input v-model="activeInfo.name" maxlength="9" show-word-limit></el-input>
							</el-form-item>
							<el-form-item label="活动价格:" prop="activity_price">
								<el-input v-model="activeInfo.activity_price"><i slot="suffix">元</i></el-input>
							</el-form-item>
							<el-form-item label="划线价格:" prop="crossed_price">
								<el-input v-model="activeInfo.crossed_price"><i slot="suffix">元</i></el-input>
							</el-form-item>
							<el-form-item label="拼团人数:" prop="member_count" v-if="activeInfo.type == 2">
								<el-input v-model="activeInfo.member_count" type="number" onKeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))"><i slot="suffix">位</i></el-input>
							</el-form-item>
							<el-form-item label="拼团商品:" prop="goods_id" v-if="activeInfo.type == 2">
								<el-input v-model="activeInfo.goods_id" placeholder="点击选择快速选择拼团商品"></el-input>
								<span style="cursor:pointer;color:#34a1e0;" @click="openGoodsView">点这里快速选择拼团商品</span>
							</el-form-item>
							<el-form-item label="活动库存:" prop="goods_number" v-if="activeInfo.type == 2">
								<el-input v-model="activeInfo.goods_number"><i slot="suffix">件</i></el-input>
							</el-form-item>
							<el-form-item label="活动时间:" prop="end_time">
								<el-date-picker value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="选择日期时间" v-model="activeInfo.end_time"
									style="width: 200px"></el-date-picker>
							</el-form-item>
							<el-form-item label="是否需要报名:" prop="is_sign">
								<el-select v-model="activeInfo.is_sign" clearable>
									<el-option :value="0" label="否">否</el-option>
									<el-option :value="1" label="是">是</el-option>
								</el-select>
							</el-form-item>
							<el-form-item label="邮箱填写:" prop="is_email">
								<el-radio-group v-model="activeInfo.is_email" >
									<el-radio :label="0">不显示</el-radio>
									<el-radio :label="1">显示</el-radio>
								</el-radio-group>
							</el-form-item>
							<el-form-item label="虚拟人数:" prop="fictitious" v-if="admin_type == 1 || admin_id == 2">
								<el-input v-model="activeInfo.fictitious"></el-input>
							</el-form-item>
							<el-form-item label="详情内容:" prop="content" class="ueditor">
								<quill-editor class="ql-editor" ref="myQuillEditor" v-model="activeInfo.content" :options="editorOption"></quill-editor>
								<!-- <vue-ueditor-wrap :config="textConfig" v-model="activeInfo.content"></vue-ueditor-wrap> -->
							</el-form-item>
						</el-form>
					</div>
				</el-col>
				<el-col :span="8">
					<mobilePhone type="0" :content="activeInfo.content" top="200" :info="activeInfo"></mobilePhone>
				</el-col>
			</el-row>
		</el-card>

		<el-card class="box-card">
			<div slot="header" class="clearfix title">支付凭证</div>
			<el-row :gutter="20">
				<el-col :span="12">
					<div class="activity-info">
						<el-form ref="activeInfo" :model="activeInfo" :rules="activeRules" label-width="120px">
							<el-form-item label="核销码:" prop="rule">
								<quill-editor class="ql-editor" ref="myQuillEditor" v-model="activeInfo.rule" :options="editorOption"></quill-editor>
							</el-form-item>
						</el-form>
					</div>
				</el-col>
				<el-col :span="8">
					<mobilePhone type="1" :content="activeInfo.rule" top="100" :info="activeInfo"></mobilePhone>
				</el-col>
			</el-row>
		</el-card>

		<el-card class="box-card">
			<div slot="header" class="clearfix title">分销设置</div>
			<el-row :gutter="20">
				<el-col :span="12">
					<div class="activity-info">
						<el-form ref="activeInfo" :model="activeInfo" :rules="activeRules" label-width="120px">
							<el-form-item label="分销层级:" prop="level">
								<el-input-number v-model="activeInfo.level" :min="0" :max="2" label="分销层级"></el-input-number>
							</el-form-item>
							<el-form-item label="收益类型:" prop="distribution_type">
								<el-radio v-model="activeInfo.distribution_type" v-for="(item,index) in radioList" :key="index" :label="item.value">{{item.name}}</el-radio>
							</el-form-item>
							<el-form-item label="一级收益:" prop="first_profit" v-if="activeInfo.level > 0">
								<el-input placeholder="请输入内容" v-model="activeInfo.first_profit">
									<template v-if="activeInfo.distribution_type == 0" slot="append">元</template>
									<template v-else slot="append">％</template>
								</el-input>
							</el-form-item>
							<el-form-item label="二级收益:" prop="second_profit" v-if="activeInfo.level == 2">
								<el-input placeholder="请输入内容" v-model="activeInfo.second_profit">
									<template v-if="activeInfo.distribution_type == 0" slot="append">元</template>
									<template v-else slot="append">％</template>
								</el-input>
							</el-form-item>
							<el-form-item label="海报图片:" prop="poster">
								<el-upload class="avatar-uploader" action="fakeaction" :show-file-list="false" :http-request=" function(res) { return upload(res, 1); } ">
									<img v-if="activeInfo.poster" :src="activeInfo.poster" class="avatar">
									<i v-else class="el-icon-plus avatar-uploader-icon"></i>
								</el-upload>
								<p style="color: #999;">建议尺寸600*750px</p>
							</el-form-item>
							<el-form-item label="客服二维码:" prop="service_code">
								<el-upload class="avatar-uploader" action="fakeaction" :show-file-list="false" :http-request=" function(res) { return upload(res, 2); } ">
									<img v-if="activeInfo.service_code" :src="activeInfo.service_code" class="avatar">
									<i v-else class="el-icon-plus avatar-uploader-icon"></i>
								</el-upload>
							</el-form-item>
							<el-form-item label="客服名称:" prop="service_name">
								<el-input v-model="activeInfo.service_name"></el-input>
							</el-form-item>
							<el-form-item label="客服电话:" prop="service_phone">
								<el-input v-model="activeInfo.service_phone" maxlength="11" show-word-limit></el-input>
							</el-form-item>
							<el-form-item label="活动状态:" prop="status">
								<el-switch v-model="activeInfo.status" :active-value="1" :inactive-value="2"></el-switch>
							</el-form-item>
						</el-form>
					</div>
				</el-col>
				<el-col :span="8">
					<mobilePhone type="3" top="100" :info="activeInfo"></mobilePhone>
				</el-col>
			</el-row>
		</el-card>
		<div class="btn-group">
			<el-button>取消</el-button>
			<el-button type="primary" @click="submit('activeInfo')">提交</el-button>
		</div>
	</div>
</template>

<script>
	import mobilePhone from '@/components/mobile-phone';
	import md5 from 'md5'
	import 'quill/dist/quill.core.css'; // import styles
	import 'quill/dist/quill.snow.css'; // for snow theme
	import 'quill/dist/quill.bubble.css'; // for bubble theme
	import {
		quillEditor,
		Quill
	} from 'vue-quill-editor';
	import {
		container,
		addQuillTitle
	} from 'quill-video-image-module';
	import {
		ImageExtend,
		QuillWatch
	} from 'quill-video-image-module';
	import {
		VideoExtend,
		QuillVideoWatch
	} from 'quill-video-image-module';

	// 引入video模块并注册
	import video from 'quill-video-image-module/video';
	Quill.register(video, true);

	Quill.register('modules/ImageExtend', ImageExtend);
	Quill.register('modules/VideoExtend', VideoExtend);
	import goods from '@/components/layer-dialog/activity-good-recommend.vue';
	export default {
		components: {
			quillEditor,
			mobilePhone,
			goods
		},
		data() {
			return {
				textConfig: {
					// 编辑器不自动被内容撑高
					autoHeightEnabled: false,
					// 初始容器高度
					initialFrameHeight: 800,
					// 初始容器宽度
					initialFrameWidth: '100%',
					serverUrl: `${this.$domain}api/Upimg/UpImg`,
					UEDITOR_HOME_URL: '/UEditor/'
				},
				disabled: false,
				admin_type: localStorage.getItem('admin_type'),
				title: '添加活动',
				radioList: [{
						value: 0,
						name: '固定收益'
					},
					{
						value: 1,
						name: '比例收益'
					}
				],
				fictitious: '',
				goods_simg: [],
				activeInfo: {
					name: '',
					title: '演示活动：电脑端点击推广按钮，在手机上预览活动',
					subtitle: '演示活动：活动副标题',
					activity_price: 33,
					crossed_price: 99,
					status: 1,
					distribution_type: 0,
					level: 1,
					service_name: '',
					fictitious: 0,
					service_phone: '',
					first_profit: 1,
					second_profit: 0,
					image: 'https://jiajudashi.oss-cn-shenzhen.aliyuncs.com/static/images/other/2020-09-09/20200909/dbe42af046fb96237b1f6dc3cb8cf37c.jpeg',
					poster: 'https://jiajudashi.oss-cn-shenzhen.aliyuncs.com/static/images/other/2020-09-08/20200908/74ef4fe32dadb5b8eed1da8084f5f4f7.jpg',
					service_code: '',
					end_time: '',
					content: '<p>我是内容活动详情内容，支持富文本编辑，可以添加文本、图片、视频、超链接等，支持富文本编辑。</p><p>实时手机版效果预览，请看PC编辑器右边。</p><p><img src="https://jiajudashi.oss-cn-shenzhen.aliyuncs.com/static/images/other/2020-09-09/20200909/c28947a30621f169c345d712b6ff01e2.jpg"></p>',
					rule: '<p>这里是用户购买后显示的页面内容，可以引导用户到店使用权益，进群，或者添加客服继续完成活动流程。</p><p>内容可以添加文本、图片、视频、超链接等，支持富文本编辑。</p><p>编辑状态下实时预览内容，展示在编辑器右边。</p><p><img src="https://jiajudashi.oss-cn-shenzhen.aliyuncs.com/static/images/other/2020-09-09/20200909/731deb1fceb40a65f48963a66a076172.jpg"></p>',
					is_sign: 0,
					goods_simg: '',
					member_count:2,
					goods_number:"",
					type:1,
					goods_id:"",
					is_email:0
				},
				activeRules: {
					name: [{
						required: true,
						message: '必填'
					}],
					is_sign: [{
						required: true,
						message: '必填'
					}],
					fictitious: [{
						required: true,
						message: '必填'
					}],
					title: [{
						required: true,
						message: '必填'
					}],
					subtitle: [{
						required: true,
						message: '必填'
					}],
					end_time: [{
						required: true,
						message: '必填'
					}],
					crossed_price: [{
						required: true,
						message: '必填'
					}],
					level: [{
						required: true,
						message: '必填'
					}],
					first_profit: [{
						required: true,
						message: '必填'
					}],
					second_profit: [{
						required: true,
						message: '必填'
					}],
					content: [{
						required: true,
						message: '必填'
					}],
					activity_price: [{
						required: true,
						message: '必填'
					}],
					image: [{
						required: true,
						message: '必填'
					}],
					goods_simg: [{
						required: true,
						message: '必填'
					}],
					poster: [{
						required: true,
						message: '必填'
					}],
					service_code: [{
						required: true,
						message: '必填'
					}],
					rule: [{
						required: true,
						message: '必填'
					}],
					service_name: [{
						required: true,
						message: '必填'
					}],
					service_phone: [{
						required: true,
						message: '必填'
					}],
					member_count: [{
						required: true,
						message: '必填'
					}],
					goods_number: [{
						required: true,
						message: '必填'
					}],
					type: [{
						required: true,
						message: '必填'
					}],
					is_email: [{
						required: true,
						message: '必填'
					}]
				},
				// 富文本框参数设置
				editorOption: {
					modules: {
						ImageExtend: {
							loading: true, // 可选参数 是否显示上传进度和提示语
							name: 'file[]', // 图片参数名
							size: 1, // 可选参数 图片大小，单位为M，1M = 1024kb
							action: `${this.$domain}api/Upimg/UpImg`, // 服务器地址, 如果action为空，则采用base64插入图片
							// response 为一个函数用来获取服务器返回的具体图片地址
							// 例如服务器返回{code: 200; data:{ url: 'baidu.com'}}
							// 则 return res.data.url
							response: res => {
								return res.datas[0];
							},
							headers: () => {}, // 可选参数 设置请求头部
							start: () => {}, // 可选参数 自定义开始上传触发事件
							end: () => {}, // 可选参数 自定义上传结束触发的事件，无论成功或者失败
							error: () => {}, // 可选参数 自定义网络错误触发的事件
							change: (xhr, formData) => {
								formData.append('timestamp', Math.round(new Date() * 1000));
								formData.append('port', 'pc');
								formData.append('sign', this.getSign());
								formData.append('key', localStorage.getItem('token'));
							}, // 可选参数 每次选择图片触发，也可用来设置头部，但比headers多了一个参数，可设置formData
							sizeError: () => {
								this.$message({
									message: '图片不能大于1M',
									type: 'warning'
								});
							}
						},
						VideoExtend: {
							loading: true,
							name: 'file[]',
							size: 100, // 可选参数 视频大小，单位为M，1M = 1024kb
							action: `${this.$domain}api/Upimg/UpVideo`, // 视频上传接口
							headers: xhr => {
								// set custom token(optional)
							},
							response: res => {
								// video uploaded path
								// custom your own
								return res.datas;
							},
							change: (xhr, formData) => {
								formData.append('timestamp', Math.round(new Date() * 1000));
								formData.append('port', 'pc');
								formData.append('sign', this.getSign());
								formData.append('key', localStorage.getItem('token'));
							}, // 可选参数 每次选择图片触发，也可用来设置头部，但比headers多了一个参数，可设置formData
							sizeError: () => {
								this.$message({
									message: '视频不能大于100M',
									type: 'warning'
								});
							}
						},
						toolbar: {
							container: container, // container为工具栏，此次引入了全部工具栏，也可自行配置
							handlers: {
								image: function() {
									// 劫持原来的图片点击按钮事件
									QuillWatch.emit(this.quill.id);
								},
								video: function() {
									QuillVideoWatch.emit(this.quill.id);
								}
							}
						}
					}
				}
			};
		},
		methods: {
			delVice(index,type){
				this.goods_simg.splice(index,1)
			},
			// 初始化
			init() {
				if (this.$route.query.type == 1) {
					this.$route.meta.title = '编辑活动'
					this.title = '编辑活动'
					let data = {
						activity_id: this.$route.query.id
					}
					this.$http(this.$ApiList.ActivityInfo, data).then(res => {
						this.activeInfo = res.datas
						this.fictitious = res.datas.fictitious
						if(res.datas.goods_simg.length){
							this.goods_simg = res.datas.goods_simg
						}
					});
				}
			},
			submit(formName) {
				if(this.activeInfo.level == 0){
					this.activeInfo.first_profit = 0;
					this.activeInfo.second_profit = 0;
				}
				let TotalPrice = Number(this.activeInfo.first_profit) + Number(this.activeInfo.second_profit);
				if (TotalPrice > Number(this.activeInfo.activity_price)) {
					this.$layer.msg('分销收益不能大于活动价格')
					return
				}

				if (this.activeInfo.fictitious < this.fictitious) {
					this.$layer.msg('现在的虚拟人数不能小于之前的虚拟人数')
					return
				}
				
				if(this.goods_simg.length){
					this.activeInfo.goods_simg = this.goods_simg.join(',')
				}
				if(this.activeInfo.type == 2){
					if(this.activeInfo.member_count<1 || this.activeInfo.member_count == ''){
						this.$layer.msg('拼团必填拼团人数并且大于0')
						return
					}
				}
				this.$refs[formName].validate((valid) => {
					if (valid) {
						this.activeInfo.store_id = localStorage.getItem('store_id')
						if (this.$route.query.type == 0 || this.$route.query.type == undefined) {
							this.$http(this.$ApiList.UpActivityInfo, this.activeInfo).then(res => {
								this.$layer.msg(res.datas);
								this.$router.push({
									path: '/activity_list'
								})
							});
						} else {
							this.$http(this.$ApiList.UpdateActivityInfo, this.activeInfo).then(res => {
								this.$layer.msg(res.datas);
								this.$router.push({
									path: '/activity_list'
								})
							});
						}
					} else {
						this.$layer.msg('请填写完整信息后提交')
					}
				});
			},
			getSign() {
				let data = {
					key: localStorage.getItem('token'),
					timestamp: Math.round(new Date() * 1000),
					port: 'pc'
				}
				// 获取签名开始
				let obj = 'jjds2020+'
				let newObj = this.objKeySort(data)
				for (let i in newObj) {
					obj += i + '=' + newObj[i] + '&'
				}
				obj = obj.substring(0, obj.length - 1)
				obj += '+jjds2020'
				obj = md5(obj)
				return obj
			},
			// 参数排序
			objKeySort(obj) {
				var newkey = Object.keys(obj).sort();
				var newObj = {};
				for (var i = 0; i < newkey.length; i++) {
					newObj[newkey[i]] = obj[newkey[i]];
				}
				return newObj;
			},
			// 图片上传 
			upload(params, type) {
				const file = params.file,
					isJPGPNG = file.type === 'image/jpeg' || 'image/png',
					isLt500KB = file.size / 1024 <= 500;
				if (!isJPGPNG) {
					this.$message.error('只能上传图片格式png、jpg!');
					return;
				}
				if (!isLt500KB) {
					this.$message.error('图片不能大于500K!');
					return;
				}
				const form = new FormData();
				form.append('file[]', file);

				this.$http(this.$ApiList.publicUpload, form).then(res => {
					switch (Number(type)) {
						case 0:
							this.activeInfo.image = res.datas[0];
							break;
						case 1:
							this.activeInfo.poster = res.datas[0];
							break;
						case 2:
							this.activeInfo.service_code = res.datas[0];
							break;
						case 3:
							this.goods_simg.push(res.datas[0])
					}
				});
			},
			// 快速选择拼团商品
			openGoodsView(){
				this.$layer.iframe({
					title: '选择商品',
					maxmin: true,
					area: ['50%', '60%'],
					content: {
						content: goods, //传递的组件对象
						parent: this, //当前的vue对象
						data: {
							goods_ids:String(this.activeInfo.goods_id),
							no_store_id: true
						} //props
					}
				});
			},
			setGoodsId(id){
				this.activeInfo.goods_id = id;
			}
		},
		created() {
			this.init();
		}
	};
</script>
<style lang="scss">
	.ueditor{
		.el-form-item__content{
			line-height: normal;
		}
	}
	.add_activity {
		
		.case-img-upload {
			display: flex;
		
			.case-img-upload-imgs {
				flex: 1;
				align-items: flex-start;
		
				.el-image {
					width: 140px;
					height: 140px;
					border: solid 1px #E5E5E5;
					margin-left: 25px;
					vertical-align: top;
				}
			}
		
			.case-img-upload-imgs-info {
				width: 100%;
				max-width: 660px;
				border: solid 1px #E5E5E5;
				margin-left: 25px;
				min-height: 390px;
		
				.case-img-upload-imgs-info-box {
					position: relative;
		
					.el-icon-error {
						position: absolute;
						font-size: 20px;
						color: #ef3030;
						right: 5px;
						top: 5px;
						z-index: 1;
						background-color: #FFF;
						border-radius: 50%;
						cursor: pointer;
					}
				}
		
				.el-image {
					width: 100%;
					vertical-align: top;
				}
			}
		
			.vice_big_box {
				position: relative;
				display: inline-block;
				vertical-align: top;
				margin-bottom: 20px;
		
				.el-icon-error {
					position: absolute;
					font-size: 20px;
					color: #ef3030;
					right: 5px;
					top: 5px;
					z-index: 1;
					background-color: #FFF;
					border-radius: 50%;
					cursor: pointer;
				}
			}
		}
		
		.title {
			margin-bottom: 0;
		}

		.activity-info .ql-container .ql-editor {
			height: 600px;

			img {
				width: 100%;
			}
		}

		.box-card {
			margin-top: 20px;
		}

		.avatar-uploader-icon {
			height: 146px;
			line-height: 146px;
			width: 146px;
		}

		.avatar {
			height: 146px;
			line-height: 146px;
			width: 146px;
		}

		.btn-group {
			margin-top: 20px;
			padding: 10px 0 20px 0;
			display: flex;
			justify-content: center;
			align-items: center;
			background-color: #fff;
		}
	}
</style>
